package com.ai.util;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * @Author jiaok
 * @Date 2024-05-14 16:18
 */
@Slf4j
public class SftpFileUploaderUtil {

    /**
     * 目标主机host
     */
    private String host;
    /**
     * 22端口
     */
    private int port = 22;

    /**
     * 登录用户名
     */
    private String username;

    /**
     * 登陆密码
     */
    private String password;

    /**
     * 远程文件地址路径
     */
    private String remoteDirectory;

    public SftpFileUploaderUtil(String host,  String username, String password, String remoteDirectory) {
        this.host = host;
        this.username = username;
        this.password = password;
        this.remoteDirectory = remoteDirectory;
    }

    /**
     * 文件上传
     * @param localFilePath
     */
    public  void uploadFile(String localFilePath) {
        JSch jsch = new JSch();
        Session session = null;
        ChannelSftp channelSftp = null;

        try {
            // 创建SSH会话
            session = jsch.getSession(username, host, port);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            // 打开SFTP通道
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();
            log.info("===========================  服务器：{}  SSH链接已建立  ===========================",this.host);
            // 获取本地文件信息
            File localFile = new File(localFilePath);
            String remoteFileName = localFile.getName();
            log.info("===========================  文件传输中......  ===========================");
            // 切换到远程目录并上传文件
            channelSftp.cd(remoteDirectory);
            channelSftp.put(Files.newInputStream(localFile.toPath()), remoteFileName);
            log.info("===========================  文件上传成功  ===========================");
        } catch (JSchException | SftpException | IOException e) {
            e.printStackTrace();
            log.info("===========================  文件上传失败 ：{} ===========================",e.getMessage());
        } finally {
            // 断开SFTP通道和SSH会话
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
    }

    public static void main(String[] args) {
        // 远程服务器连接参数
        String host = "192.168.8.194";
        int port = 22;
        String username = "jiaokang";
        String password = "jiaokang";
        String remoteDirectory = "/home/jiaokang/server/jk";

        // 本地文件路径
        String localFilePath = "D:\\package_test\\epoch_200.pth";

        // 创建上传器对象并调用上传方法
        SftpFileUploaderUtil uploader = new SftpFileUploaderUtil(host, username, password, remoteDirectory);
        uploader.uploadFile(localFilePath);
    }

}
